package thesis.filesharing.web.tags;

import java.util.HashSet;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;

import thesis.filesharing.web.auth.AuthenticationUserDetails;

public class TagFunctions {
	
	public static AuthenticationUserDetails checkAuthentication() {
		Object obj = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		if (obj instanceof String) {
			return null;
		} else {
			return (AuthenticationUserDetails) obj;
		}
	}
	
	public static Boolean isUserInRole(String roleName) {
		boolean isAuth = SecurityContextHolder.getContext().getAuthentication().isAuthenticated();
		if (isAuth) {
			AuthenticationUserDetails authUser = (AuthenticationUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
			HashSet<GrantedAuthority> authorities = (HashSet<GrantedAuthority>) authUser.getAuthorities();
			for (GrantedAuthority a : authorities) {
				if (a.getAuthority().equalsIgnoreCase(roleName)) {
					return true;
				}
			}
		}
		return false;
	}
}
